package com.airnews.ticket.ui;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.airnews.ticket.R;
import com.airnews.ticket.sql.FavoriteInfoDB;
import com.airnews.ticket.util.Constants;
import com.airnews.ticket.util.PhoneUtils;
import com.airnews.ticket.util.StringUtil;
import com.mobclick.android.MobclickAgent;

/**
 * 登陆页面
 * @author luoxz
 */
public class Welcome extends BaseActivity {
	
	private Timer progressTimer = new Timer();
	private LinearLayout progressBar;
	private boolean isCancel;
	private Handler handler = new Handler();
	
	private SharedPreferences spChannel;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.welcome);
		// 删除窗口背景
        getWindow().setBackgroundDrawable(null);
		activityList.add(this); 
		// 保存手机号码
//		if (NetIOUtils.isNetworkAvailable(this)) {
//			savePhoneNum();
//		}
		
		progressBar = (LinearLayout)findViewById(R.id.progressBar);
		
		//显示进度条
		showProgress();
		
		//取渠道ID
		try {
			//取配置文件上的值
			ApplicationInfo  info = this.getPackageManager().getApplicationInfo(getPackageName(),PackageManager.GET_META_DATA);
		    String msg1=info.metaData.getString("UMENG_CHANNEL");
		    Constants.ASID = msg1;
		    String msg2=info.metaData.getString("UMENG_SecretKey");
		    Constants.SecretKey = msg2;
		    String msg3=info.metaData.getString("UMENG_IVS");
		    Constants.IVS = msg3;
		    String msg4=info.metaData.getString("UMENG_OfficeID");
		    Constants.OfficeID = msg4;
		    
		    //第一次从配置文件取值，第二次直接从本机数据库中取值
		    String channelId = FavoriteInfoDB.selectFlySetInfoValue(this, Constants.SYSTEM_TYPE_ASID);
		    ContentValues values = new ContentValues();
			values.put("systemType", Constants.SYSTEM_TYPE_ASID);
		    if(channelId!=null && !channelId.equals("")){
		    	values.put("systemName", channelId);
		    	FavoriteInfoDB.updateFlySetInfo(this, values);
		    } else {
		    	channelId = msg1;
		    	values.put("systemName", channelId);
		    	FavoriteInfoDB.insertFlySetInfo(this, values);
		    }
		    Constants.ASID = channelId;
		    
		    String secretKey = FavoriteInfoDB.selectFlySetInfoValue(this, Constants.SYSTEM_TYPE_SECRETKEY);
		    values = new ContentValues();
			values.put("systemType", Constants.SYSTEM_TYPE_SECRETKEY);
		    if(secretKey!=null && !secretKey.equals("")){
		    	values.put("systemName", secretKey);
		    	FavoriteInfoDB.updateFlySetInfo(this, values);
		    } else {
		    	secretKey = msg2;
		    	values.put("systemName", secretKey);
		    	FavoriteInfoDB.insertFlySetInfo(this, values);
		    }
		    Constants.SecretKey = secretKey;
		    
		    String ivs = FavoriteInfoDB.selectFlySetInfoValue(this, Constants.SYSTEM_TYPE_IVS);
		    values = new ContentValues();
			values.put("systemType", Constants.SYSTEM_TYPE_IVS);
		    if(ivs!=null && !ivs.equals("")){
		    	values.put("systemName", ivs);
		    	FavoriteInfoDB.updateFlySetInfo(this, values);
		    } else {
		    	ivs = msg3;
		    	values.put("systemName", ivs);
		    	FavoriteInfoDB.insertFlySetInfo(this, values);
		    }
		    Constants.IVS = ivs;
		    
		    String officeID = FavoriteInfoDB.selectFlySetInfoValue(this, Constants.SYSTEM_TYPE_OFFICEID);
		    values = new ContentValues();
			values.put("systemType", Constants.SYSTEM_TYPE_OFFICEID);
		    if(officeID!=null && !officeID.equals("")){
		    	values.put("systemName", officeID);
		    	FavoriteInfoDB.updateFlySetInfo(this, values);
		    } else {
		    	officeID = msg4;
		    	values.put("systemName", officeID);
		    	FavoriteInfoDB.insertFlySetInfo(this, values);
		    }
		    Constants.OfficeID = officeID;
		    
		    System.out.println("channelId="+channelId);
		    System.out.println("secretKey="+secretKey);
		    System.out.println("ivs="+ivs);
		    System.out.println("officeID="+officeID);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		
		new Thread(){

			@Override
			public void run() {
				
				SystemClock.sleep(2000);
				//getRemoteInfo("1331609");FlyOrderInput
				
				if(!isCancel){
					Welcome.this.runOnUiThread(new Runnable() {
						public void run() {
							Intent it = new Intent(Welcome.this, Main.class);
							startActivity(it);
							overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
							finish();
						}
					});
				}
				
				//停止定时器
				progressTimer.cancel();
				progressTimer = null;
				
				//初始化目录
				initAppDirs();
			}
			
		}.start();
	}

	
	
	/**
	 * 显示进度条
	 */
	private void showProgress() {
		progressTimer.schedule(new TimerTask() {
			int count = progressBar.getChildCount();
			int[] drawables = {R.drawable.point_s, R.drawable.point};
			int i = 0;
			@Override
			public void run() {
				Welcome.this.runOnUiThread(new Runnable() {
					public void run() {
						if(i == count * drawables.length){
							i = 0;
						}
						ImageView img = (ImageView)progressBar.getChildAt(i%count);
						img.setImageResource(drawables[i/count]);
						i++;
					}
				});
			}
		}, 100, 500);
	}

	
	/**
	 * 初始化掌厅在SD卡上的目录
	 */
	private void initAppDirs() {
		if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
			File rootDir = new File(Environment.getExternalStorageDirectory(), Constants.DOWNLOAD_DIR);
			if(!rootDir.exists()){
				rootDir.mkdir();
			}
			File subDir = new File(rootDir, Constants.SUB_IMG_DIR);
			if(!subDir.exists()){
				subDir.mkdir();
			}
		}
	}


	@Override
	public void onBackPressed() {
		isCancel = true;
		finish();
	}
	
	/*	/**
	 * 获取并保存本手机号码
	 */
	private void savePhoneNum() {
		new Thread() {
			@Override
			public void run() {
				String phoneNum = PhoneUtils.getMdn(Welcome.this);
				Log.i("phone", phoneNum);
				if (StringUtil.isEmpty(phoneNum) || !phoneNum.matches("[0-9]{11}")) {
					//phoneNum = WebAccessor.getTel(Main.this, PhoneUtils.getImsi(Main.this));
				}
				if (StringUtil.isEmpty(phoneNum) || !phoneNum.matches("[0-9]{11}")) {
					//phoneNum = WebAccessor.getPhoneNum(Main.this);
				}
				if (!StringUtil.isEmpty(phoneNum) && phoneNum.matches("[0-9]{11}")) {
					getSharedPreferences(Constants.PREFS_FILE, MODE_PRIVATE)
							.edit()
							.putString(Constants.PHONE_NUM_KEY, phoneNum)
							.commit();
				} else {
					showDialog();
				}
			}

		}.start();
	}

	private void showDialog() {
		handler.post(new Runnable() {

			public void run() {
				new AlertDialog.Builder(Welcome.this).setIcon(
						R.drawable.alert_dialog_icon).setTitle(
						"无法获取本机手机号，请请切换到CNWAP网络后重试").setPositiveButton(
						"确定",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								finish();
							}
						}).show();
			}
		});
	}
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  
}
